<?php

include_once 'modulo.php';
include_once 'model.php';
include_once 'lib/KLogger.php';
require_once("lib/class.phpmailer.php");

$log = new KLogger ( "log/modulo.log" , KLogger::DEBUG );
$log->LogDebug("controller.php");

if (!isset($_SESSION)) {
	session_start();
}

$modulo= new modulo();
$errori= array();

// LETTURA FORM 
foreach ($_REQUEST as $k => $v) {
	if( isset($modulo[$k]))		
  		$modulo[$k]=$v;
}

$_SESSION['score']=$_REQUEST['score'];
//var_dump($modulo);

$_SESSION['modulo']=$modulo;

// VALIDAZIONE SERVER
$er = array();

//controllo codice captcha
$codice_errato=false;
$log->LogDebug("captcha:". $_REQUEST['captcha']);
$log->LogDebug("key:". $_REQUEST['key']);
if(isset($_REQUEST['captcha']) && isset($_REQUEST['key'])){
 	$captcha = $_REQUEST['captcha'];
 	$key = $_REQUEST['key'];
	if ($captcha==$key)
		$codice_errato=false;
	else 
		$codice_errato=true;
	$log->LogDebug("codice captcha:".$codice_errato);
}

if($codice_errato){
	array_push($er,'captcha');
}

$action = $_REQUEST['azione'];
$log->LogDebug("azione:".$action);
			
foreach ($_REQUEST as $k => $v) {
  if(!$modulo->isValid($k))
  	array_push($er,$k);
}
$modulo->setErrors($er);

if($action!="clear" && count($modulo->getErrors())>0){
	$action='error';
}

$urlxml = "./resources/config.xml";
$config= new SimpleXmlElement($urlxml,1,true);
$host = $config->database->host;
$dbname = $config->database->name;
$user = $config->database->user;
$pass = $config->database->password;

$from = $config->mail->from;
$dests = $config->mail->to->children();
// $to = $config->mail->to;
$server = $config->mail->server;
$subject = $config->mail->subject;
/*
$headers = 'From: '.$from. "\r\n" .
		'Reply-To: '.$from . "\r\n" .
		'X-Mailer: PHP/' . phpversion();
*/

$log->LogDebug("from: $from");
//$log->LogDebug("to: $to");
$log->LogDebug("server: $server");
//$log->LogDebug("headers: $headers");

if(isset($action)){
	
	$model = new Model($host,$dbname,$user,$pass);
	switch ($action) {
		case 'error':
			header( "Location: scheda_form.php?azione=$action" );
			return;
		break;
		case 'insert':
// 			if($model->checkUsedCode($modulo)){
// 				header( "Location: error.php?msg=codice_duplicato" );
// 				return;
// 			}
			$pkid = $model->insertUpdate($modulo);
			$log->LogDebug("pkid: $pkid");
			/*
			$message = str_replace("%1",$modulo->data,$message);
			$message = str_replace("%2",$modulo->cliente,$message);
			$message = str_replace("%3",$modulo->riferimento,$message);
			$message = str_replace("%4",$modulo->riferimento_email,$message);
			*/
			$message = $model->db2xslt($pkid,"scheda.xsl");
			$model->close();
			
			$log->LogDebug("message: $message");
			
			$subject = str_replace("%2",$modulo->cliente,$subject);
			$subject = str_replace("%3",$modulo->riferimento,$subject);
			$log->LogDebug("subject: $subject");
			
			$mailer = new PHPMailer();
			$mailer->SMTPDebug  = 2;
			$mailer->IsSMTP();
			$mailer->IsHTML(true);
			$mailer->Host = $server;
			$mailer->Helo = $from;
			// autenticazione 
			$mailer->From = $from;
			$mailer->FromName = '';
			$mailer->Subject = $subject;
			
			$mailer->CharSet= 'UTF-8';
			$mailer->Body = $message;
			for($i=0;$i<count($dests);$i++){
				$mailer->AddAddress($dests[$i]);
				$log->LogDebug("dest:".$dests[$i]);
			}
			// aggiunge email del riferimento
			$mailer->AddAddress($modulo->riferimento_email);
			$log->LogDebug("dest:".$modulo->riferimento_email);
			if($mailer->Send()) {
				$log->LogDebug("Mail Inviate con successo");
			} else {
				$log->LogError("Errore nell'invio delle mail: ".$mailer->ErrorInfo);
			}	
			header( "Location: inviato.php" );
			return;
		break;
		case 'clear':
			// pulisce sessione
			session_destroy();
			header( "Location: scheda_form.php" );
			return;
			break;
		case 'continua':
			// TODO legge 
			header( "Location: scheda_form.php" );
			return;
		break;
		default:
			header( "Location: error.php?msg=errore_generico" );
		break;
	}
} else
	header( "Location: error.php" );
?>